package com.ecjtu.stadiumre_servations.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration conf = new CorsConfiguration();
        // 1. 使用 allowedOriginPatterns 替代 allowedOrigins
        conf.addAllowedOriginPattern("*"); // 允许所有域名进行跨域调用
        conf.addAllowedOrigin("http://localhost:5173");
        conf.setAllowCredentials(true);    // 允许携带凭证

        // 2. 精简暴露的响应头，只保留必要的
        conf.addExposedHeader("Authorization");
        conf.addExposedHeader("Content-Disposition");
        conf.addAllowedHeader("*");        // 允许任何请求头
        conf.addAllowedMethod("*");        // 允许任何方法（POST、GET等）
        conf.setMaxAge(3600L);             // 预检请求的缓存时间
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", conf);
        return new CorsFilter(source);
    }
}